import { NextRequest, NextResponse } from 'next/server';
import { readdir, stat } from 'fs/promises';
import path from 'path';

interface MediaFile {
  id: string;
  name: string;
  originalName: string;
  type: 'image' | 'video' | 'document';
  size: number;
  url: string;
  uploadDate: string;
  category?: string;
}

export async function GET() {
  try {
    const uploadsDir = path.join(process.cwd(), 'public', 'uploads');
    
    // 读取uploads目录下的所有文件
    let files: string[] = [];
    try {
      files = await readdir(uploadsDir);
    } catch (error) {
      // 目录不存在时返回空数组
      return NextResponse.json({
        success: true,
        data: []
      });
    }

    const mediaFiles: MediaFile[] = [];

    for (const file of files) {
      try {
        const filePath = path.join(uploadsDir, file);
        const stats = await stat(filePath);
        
        if (stats.isFile()) {
          const ext = path.extname(file).toLowerCase();
          let type: 'image' | 'video' | 'document' = 'document';
          
          if (['.jpg', '.jpeg', '.png', '.gif', '.webp', '.svg'].includes(ext)) {
            type = 'image';
          } else if (['.mp4', '.avi', '.mov', '.mkv', '.webm'].includes(ext)) {
            type = 'video';
          }

          mediaFiles.push({
            id: file,
            name: file,
            originalName: file,
            type,
            size: stats.size,
            url: `/api/uploads/${file}`,
            uploadDate: stats.mtime.toISOString().split('T')[0],
            category: type === 'image' ? '图片' : type === 'video' ? '视频' : '文档'
          });
        }
      } catch (error) {
        // 跳过无法处理的文件
        continue;
      }
    }

    // 按上传时间倒序排列
    mediaFiles.sort((a, b) => new Date(b.uploadDate).getTime() - new Date(a.uploadDate).getTime());

    return NextResponse.json({
      success: true,
      data: mediaFiles
    });
  } catch (error) {
    console.error('Error fetching media files:', error);
    return NextResponse.json({
      success: false,
      error: '获取媒体文件失败'
    }, { status: 500 });
  }
}

export async function DELETE(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const filename = searchParams.get('filename');
    
    if (!filename) {
      return NextResponse.json({ 
        success: false, 
        error: '缺少文件名参数' 
      }, { status: 400 });
    }

    const filePath = path.join(process.cwd(), 'public', 'uploads', filename);
    
    // 删除文件
    const { unlink } = await import('fs/promises');
    await unlink(filePath);
    
    return NextResponse.json({
      success: true,
      message: '文件删除成功'
    });
  } catch (error) {
    console.error('Error deleting media file:', error);
    return NextResponse.json({
      success: false,
      error: '删除文件失败'
    }, { status: 500 });
  }
}